#!/usr/bin/env python3

## pip install PyInstaller 
## pip install -e 'packages/markitdown[all]'

import os
import sys
import subprocess
import platform
import re
import importlib.util
import shutil

PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
LAUNCHER = os.path.join(PROJECT_ROOT, "launcher.py")
PACKAGE = ("packages/markitdown/src/markitdown", "markitdown")
#CONFIG_FILE = os.path.join(PROJECT_ROOT, "config.json")

spec = importlib.util.find_spec("magika")
if spec is None:
    raise RuntimeError("magika not found, please install it first")
MAGIKA_SRC = os.path.dirname(spec.origin)
MAGIKA_DEST = "magika"
sep = ";" if platform.system() == "Windows" else ":"

def scan_imports(dir_tuple):
    imports = set()
    pattern = re.compile(r'^\s*(?:import|from)\s+([a-zA-Z0-9_\.]+)')
    dir_path, _ = dir_tuple
    for root, _, files in os.walk(os.path.join(PROJECT_ROOT, dir_path)):
        for f in files:
            if f.endswith(".py"):
                with open(os.path.join(root, f), "r", encoding="utf-8") as file:
                    for line in file:
                        match = pattern.match(line)
                        if match:
                            module = match.group(1).split('.')[0]
                            if module not in ("__future__",):
                                imports.add(module)
    return sorted(list(imports))

hidden_imports = scan_imports(PACKAGE)
print("Detected hidden imports:", hidden_imports)

# 清理旧构建
for d in ["build", "dist"]:
    shutil.rmtree(os.path.join(PROJECT_ROOT, d), ignore_errors=True)
spec_file = os.path.join(PROJECT_ROOT, "markitdown.spec")
if os.path.exists(spec_file):
    os.remove(spec_file)

cmd = [
    sys.executable, "-m", "PyInstaller",
    "--onedir",
    "--name", "markitdown",
    "--clean",
    "--noconfirm",
    f"--add-data={os.path.join(PROJECT_ROOT, PACKAGE[0])}{sep}{PACKAGE[1]}",
    f"--add-data={MAGIKA_SRC}{sep}{MAGIKA_DEST}",
    LAUNCHER
] + [f"--hidden-import={h}" for h in hidden_imports]

# 加上模型目录
MAGIKA_MODELS = os.path.join(MAGIKA_SRC, "models")
if os.path.exists(MAGIKA_MODELS):
    cmd.append(f"--add-data={MAGIKA_MODELS}{sep}magika/models")

print("\n 正在执行 PyInstaller 打包 ...")
subprocess.run(cmd, check=True)

dist_dir = os.path.join(PROJECT_ROOT, "dist", "markitdown")

# 拷贝配置文件
"""
if os.path.exists(CONFIG_FILE):
    shutil.copy(CONFIG_FILE, dist_dir)
    print(f"已复制 config.json 到 {dist_dir}")
else:
    print("未找到 config.json,跳过复制")
"""
print("\n构建完成,最终可执行目录：")
print(f"   {dist_dir}")
print("   可直接运行： markitdown.exe --help 或 ./markitdown test.pdf > test.md")
